import { getUserInfo, login } from '@/api/user'
import { constantRoutes, resetRouter } from '@/router'

import { getToken, removeToken, setToken } from '@/utils/auth'

const state = {
  token: getToken(),
  userInfo: {},
  routes: constantRoutes

}
const mutations = {
  setRoutes(state, newRoutes) {
    state.routes = [...constantRoutes, ...newRoutes]
  },
  setToken(state, token) {
    state.token = token // 将token保存到vuex中
    setToken(token) // 将token保存到cookie中
  },
  // 为了好维护 再封装一个专用于清除token的mutation
  removeToken(state) {
    state.token = null
    // 清除cookie
    removeToken()
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  removeUserInfo(state) {
    state.userInfo = {} // 用户信息擦除  防止别有用心的人 在你退出系统后 看控制台
  }
}
const actions = {
  logout({ commit }) {
    // 移除token和userInfo
    commit('removeToken')
    commit('removeUserInfo')
    // 重置路由
    // commit('setRoutes', [])
    resetRouter()
  },
  async login({ commit }, obj) {
    // setTimeout(() => {
    //   commit('setToken', 'token')
    // }, 3000)

    const res = await login(obj)
    // console.log(res)
    commit('setToken', res)
  },
  async getUserInfo({ commit }) {
    // setTimeout(() => {
    //   commit('setUserInfo', {
    //     name: '张三'
    //   })
    // }, 3000)
    const res = await getUserInfo()
    console.log(res)
    commit('setUserInfo', res)
    return res
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
